<!--
 * @Author: Siogo 你的邮箱
 * @Date: 2025-10-16 10:16:31
 * @LastEditors: Siogo 你的邮箱
 * @LastEditTime: 2025-10-16 10:16:42
 * @FilePath: /frontend/src/views/tb/group/form.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <BasicModal v-bind="$attrs" :showFooter="true" @register="registerModal" @ok="handleSubmit" width="40%">
    <template #title>
      <Icon icon="ant-design:group-outlined" class="pr-1 m-1" />
      <span>{{ getTitle }}</span>
    </template>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup name="ViewsTbGroupForm">
  import { ref, computed } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  const emit = defineEmits(['success', 'register']);

  const { showMessage } = useMessage();
  const record = ref<any>({});

  const getTitle = computed(() => (record.value.id ? '编辑设备组' : '新增设备组'));

  const inputFormSchemas: FormSchema[] = [
    {
      label: '设备分组名称',
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        placeholder: '请输入设备分组名称',
      },
      required: true,
    },
    {
      label: '设备分组描述',
      field: 'description',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        placeholder: '请输入设备分组描述',
        rows: 4,
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ loading: true });
    record.value = { ...data };
    await resetFields();

    if (data?.id) {
      // 编辑模式，设置表单值
      setFieldsValue(data);
    }

    setModalProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setModalProps({ confirmLoading: true });

      // 模拟保存逻辑
      const result = {
        ...data,
        id: record.value.id || Date.now().toString(),
        deviceCount: record.value.deviceCount || 0,
        createdTime: record.value.createdTime || new Date().getTime(),
      };

      showMessage(`${record.value.id ? '编辑' : '新增'}设备组成功！`);
      setTimeout(closeModal);
      emit('success', result);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage('表单验证失败');
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
